<?php 

namespace Weixin\Model;

use Common\Model\RelationModel;

class WorksModel extends RelationModel{
    
    //array(填充字段,填充内容,[填充条件,附加规则])
    protected $_auto	 =	 array(
        array('iftj', 0, self::MODEL_INSERT,'string'),
        array('ifindex', 0, self::MODEL_INSERT,'string'),
        array('status', 0, self::MODEL_INSERT,'string'),
        array('sort', '0', self::MODEL_INSERT,'string'),
        array('create_time','time',self::MODEL_INSERT,'function')
    );
    
    //关联属性是以当前模型为主
    protected $_link = array(
        //关联操作步骤
        'works_makestep'=>array(
            'mapping_type'      => self::HAS_MANY,
            'foreign_key'       => 'workid',
            'class_name'        => 'works_makestep',
            'mapping_fields'    => array('id','scontent','simage'),
            'mapping_order'     => 'id ASC'
        ),
        //关联材料
        'works_materials'=>array(
            'mapping_type'  => self::HAS_MANY,
            'foreign_key'   => 'workid',
            'class_name'    => 'works_materials',
            'mapping_fields'=>'id,mname,mvalue',
            'mapping_order' =>' id ASC'
        )
    );
    
    /**
     * 添加作品信息模型
     * @param $data 页面POST的数
     * @return boolean|error
    */
    public function addModel($data) {
        if (empty($data)) {
            $this->error = '添加数据不能为空！';
            return false;
        }
        //终极栏目设置
        if(empty($data['cateid'])){
            $this->error='请选择发布的类型';
            return false;
        }
        if(mb_strlen($data['title'],'utf-8')<1 || mb_strlen($data['title'],'utf-8')>30){
            $this->error='食谱名称不能为空且不能超过30个字符';
            return false;
        }
        if(empty($data['image'])){
            $this->error='请上传食谱主图';
            return false;
        }
        if(empty($data['content'])){
            $this->error='请添加食谱说明';
            return false;
        }
    
        if(empty($data['mname'][0]) || empty($data['mvalue'][0])){
            $this->error='请至少填写一项食谱用料';
            return false;
        }
        //yf start
        foreach($data['mname'] as $k => $v)
        {
            if(empty($v) && empty($data['mvalue'][$k]))
            {
                unset($data['mname'][$k]);
                unset($data['mvalue'][$k]);
            }
            elseif(empty($v) || empty($data['mvalue'][$k]))
            {
                $this->error='请补全食谱用料名称或者是用量';
                return false;
            }
        }
        //yf end
        
        $data['status'] = 0;
        $mname = $data['mname'];
        $mvalue = $data['mvalue'];
        $simage = $data['simage'];
        $scontent = $data['scontent'];
        $result = $this->create($data, 1);
        if($result) {
            //添加数据
            $workid = $this->add($result);
            if ($workid) {
                //更新材料
                if($mname){
                    $datas['workid']=$workid;
                    foreach($mname as $key=>$value){
                        //添加附件到产品附件表
                        $datas['mname']=$value;
                        $datas['mvalue']=$mvalue[$key];
                        M('works_materials')->data($datas)->add();
                    }
                }
                unset($datas);
                //更新步骤
                if($scontent){
                    $arr['workid']=$workid;
                    foreach($scontent as $key=>$value){
                        //添加附件到产品附件表
                        $arr['scontent']=$value;
                        $arr['simage']=$simage[$key];
                        M('works_makestep')->data($arr)->add();
                    }
                }
                return $workid;
            } else {
                $this->error = '食谱添加失败';
                return false;
            }
        } else {
            return false;
        }
    }
    
    /**
     * 获取兄弟分类
     * @param unknown $cateid
     * @return unknown
     */
    public function getBorCate($cateid)
    {
        $parentId = M('Category')->where(array('cateid' => $cateid))->getField('parentid');
        $borCate = array();
        if($parentId != 1)
        {
            $borCate[] = array(
                    'cateid' => $parentId,
                    'catename' => '返回分类'
            );
        }
        $tempArr = D('Weixin/Index')->getCategory($parentId, false);
        if($tempArr)
        {
            foreach($tempArr as $tk => $tv)
            {
                $borCate[] = $tv;
            }
        }
        $arr = array();
        if($borCate)
        {
            $num = 0;
            foreach($borCate as $k => $v)
            {
                $arr[$num][] = $v;
                if(($k + 1) % 4 == 0)
                {
                    $num++;
                }
            }
        }
        return $arr;
    }
    
    /**
     * 获取子分类Id
     * @param unknown $cateid
     * @return unknown
     */
    public function getChlidCateid($cateid)
    {
        $arr[] = $cateid;
        $child = D('Weixin/Index')->getCategory($cateid, false);
        if(count($child) > 0)
        {
            foreach($child as $k => $v)
            {
                $arr[] = $v['cateid'];
            }
        }
        return implode(",", $arr);
    }
    
    /**
     * 获取
     * @param unknown $cateid
     * @param string $title
     * @param unknown $first
     * @param unknown $last
     * @return string
     */
    public function getWorkList($cateid, $title = '', $first, $last)
    {
        $where = '';
        if($title)
        {
            $where = " and W.title like '%".$title."%'";
        }
        else 
        {
            if($cateid != 0)
            {
                $where = " and W.cateid IN(".$cateid.")";
            }
        }
        $list = M()
        ->table(array(C('DB_PREFIX').'works' => 'W', C('DB_PREFIX').'user' => 'S'))
        ->where('W.type=1 and W.status=1 and W.userid=S.userid'.$where)
        ->order('create_time desc')
        ->field('W.workid, W.title, W.content, W.image, W.goodnum, W.msgnum, W.create_time, S.nickname, S.uavatar')
        ->limit($first, $last)
        ->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['nickname'] = hy_substr($v['nickname'], 5, true);
                $list[$k]['content'] = hy_substr($v['content'], 12);
            }
        }
        return $list;
    }
    
    /**
     * 删除作品
     * @param $data
     * @return bool
     */
    public function deleteWorks($data){
        if(empty($data)){
            $this->error = '食谱删除失败';
            return false;
        }
        $where['workid']=$data;
        $item=$this->field('userid,status')->where($where)->find();
        if($item['status']==true){
            $savearr['worksnum'] = array('exp','worksnum-1');
            $savearr['upoint'] = array('exp','upoint-10');
        }
        $status=$this->relation(true)->where($where)->delete();
        if($status!==false){
            //减去数量与积分操作
            M('User')->where(array('userid'=>$item['userid']))->save($savearr);
            //删除产品主图
            service("Attachment")->api_delete('works-' . $data);
            return true;
        }else{
            return false;
        }
    }
    
    public function getDynamic($order, $first, $last)
    {
        $list = M()
        ->table(array(C('DB_PREFIX').'works' => 'W', C('DB_PREFIX').'user' => 'S'))
        ->where('W.type=1 and W.status=1 and W.userid=S.userid')
        ->order($order)
        ->field('W.workid, W.title, W.content, W.image, W.goodnum, W.msgnum, W.create_time, S.nickname, S.uavatar')
        ->limit($first, $last)
        ->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['nickname'] = hy_substr($v['nickname'], 5, true);
                $list[$k]['content'] = hy_substr($v['content'], 12);
            }
        }
        return $list;
    }
    
}